//
//  ImageMessage.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/11/14.
//

import SwiftUI
import Kingfisher

struct ImageMessage: View {
    var isMe : Bool
    var url  : String = ""
    @State var image: UIImage? = UIImage(named: "placeholder")
    @State var width: CGFloat = 100
    @State var height: CGFloat = 100
    @State var screenWidth : CGFloat = 300
    @State var showZoomView : Bool = false
    var body: some View {
        GeometryReader { geometry in
            HStack(alignment: .top,spacing: 0) {
                if isMe {
                    Spacer()
                }
                KFImage.url(URL(string: url))
                        .onSuccess { r in
                            let size = getFrame(img: r.image)
                            self.width = size.0
                            self.height = size.1
                            self.image = r.image
                        }
                        .resizable()
                    .scaledToFit()
                    .frame(maxWidth:screenWidth,maxHeight:screenWidth)
                    .frame(width:width,height:height)
                    .onTapGesture {
                        self.showZoomView.toggle()
                    }
                if !isMe {
                    Spacer()
                }
            }
            .onAppear() {
               print("ImageMessage:\(url)")
                self.screenWidth = geometry.size.width * 3 / 4
            }
        }.frame(height:height)
            .padding(5)
            .sheet(isPresented: self.$showZoomView) {
                PhotoView(image:self.image!)
            }
    }

    func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
        URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
    }

    func getFrame(img:UIImage) -> (CGFloat,CGFloat) {
        let width = img.size.width
        let height = img.size.height
        var width2 = width
        var height2 = height
        if width >= height {
            width2 =  screenWidth
            height2 = width2 * height / width
        } else {
            height2 =  screenWidth
            width2 = height2 * width / height
        }

        return (width2,height2)

    }
}

struct ImageMessage_Previews: PreviewProvider {
    static var previews: some View {
        ImageMessage(isMe: true, url: "https://www.zhuiso.cn/shequ//Uploads/2022-11-14/63723ea070c0f.jpg",image: UIImage(named: "background")!)
    }
}
